package com.hmjk.health.home;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.HttpConf;
import com.hmjk.health.card.CardFragment;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.DEV_FACE;
import com.hmjk.health.util.DEV_POWER;
import com.hmjk.health.util.DEV_SET;
import com.hmjk.health.util.QRCodeActivity;
import com.hmjk.health.views.RoundImageView;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class DeviceManagerActivity extends Activity implements OnClickListener{
	private HealthApp mApp = null;	
	private DEV_DATA mDev;
	private DEV_SET mSetData = null;
	
	private Button butEdit = null, butAdmin = null, butOb = null;
	private RoundImageView vPhoto = null;
	private TextView tvAccount = null, tvPhone = null, tvAuthor = null, tvWarning = null;
	private TextView tvBattery;
	private DEV_POWER mPower;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		mDev = (DEV_DATA) getIntent().getSerializableExtra("dev");
		
		setContentView(R.layout.devicemanager_activity);
		
		vPhoto = (RoundImageView)findViewById(R.id.photo);
		if(mDev.admin == 1)
			vPhoto.setOnClickListener(this);
		else
			vPhoto.setOnClickListener(null);
		
		tvAccount = (TextView)findViewById(R.id.account);
		tvPhone = (TextView)findViewById(R.id.phone);
		tvAuthor = (TextView)findViewById(R.id.authority);
		tvWarning = (TextView)findViewById(R.id.warning);
		tvBattery = (TextView)findViewById(R.id.battery);
		TextView toManufactrue = (TextView)findViewById(R.id.check_manufactrue);
		String ssignup = getResources().getString(R.string.to_manufactrue);
		toManufactrue.setText(Html.fromHtml(ssignup));
		toManufactrue.setOnClickListener(this);
		
		Button invite = (Button) findViewById(R.id.but_share);
		invite.setOnClickListener(this);
		butEdit = (Button)findViewById(R.id.edit);
		butAdmin = (Button)findViewById(R.id.but_admin);
		butOb = (Button)findViewById(R.id.but_ob);
		butEdit.setOnClickListener(this);
		butAdmin.setOnClickListener(this);
		butOb.setOnClickListener(this);
		
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		refreshData();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);
		updateData();
		updateView();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(mReceiver);
		mApp.dismissWaiting();
	}
	
	private String refreshing = null;
	private void refreshData(){
		boolean ok = mApp.getDataManager().refreshData(DataManager.F_DEVICE_SETTINGS, mDev.id);
		if(ok){
			refreshing = new String(DataManager.F_DEVICE_SETTINGS);
		}
		
		ok = mApp.getDataManager().refreshData(DataManager.F_DEVICE_POWER, mDev.id);
		if(ok){
			if(refreshing == null)
				refreshing = new String(DataManager.F_DEVICE_POWER);
			else
				refreshing += ":" + DataManager.F_DEVICE_POWER;
		}
		
		if(refreshing != null){
			mApp.showWaitting(this, null);
		}
	}
	
	private void updateData(){
		mSetData = null;
		String[] arg1 = new String[2];
		arg1[0] = "DEV_TID";
		arg1[1] = mDev.id;
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, arg1);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				if(ar.length() > 0){
					JSONObject e = ar.getJSONObject(0);
					mDev.id = e.getString("tid");
					mDev.name = e.getString("name");
						
					String ss = e.getString("status");
					mDev.status = Integer.parseInt(ss);
						
					mDev.type = e.getString("type");
						
					String a = e.getString("admin");
					mDev.admin = Integer.parseInt(a);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		String[] arg2 = new String[1];
		arg2[0] = mDev.id;
		
		DEV_SET[] data = (DEV_SET[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_SETTINGS, arg2);
		if(data != null){
			mSetData =  data[0];
		}
		
		String arg3[] = new String[1];
		arg3[0] = mDev.id;
		DEV_POWER[] powers = (DEV_POWER[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_POWER, arg3);
		if((powers != null) && (powers[0] != null)){
			mPower = powers[0];
		}else{
			mPower = null;
		}
	}
	
	private void updateView(){
		if(mDev == null){
			return;
		}
		
		String name = mDev.name;
		if((name == null) || name.isEmpty()){
			name = getResources().getString(R.string.noName);
		}
		tvAccount.setText(name);
		
		if(mDev.admin == 1){
			//administrator
			tvAuthor.setText(R.string.you_are_admin);
			butAdmin.setVisibility(View.VISIBLE);
			butAdmin.setText(R.string.abandon_admin);
			butAdmin.setTextColor(0xff444444);
			butAdmin.setBackgroundResource(R.drawable.but_yellow_bg);
			butOb.setVisibility(View.GONE);
			tvWarning.setVisibility(View.INVISIBLE);
			tvWarning.setText(R.string.dev_manager_warning);
			tvWarning.setBackgroundColor(0xFFF9C46F);
		}else if(mDev.admin == 2){
			//not have a administrator
			tvAuthor.setText(R.string.you_are_ob);
			butAdmin.setVisibility(View.VISIBLE);
			butAdmin.setText(R.string.acquire_admin);
			butAdmin.setTextColor(0xffffffff);
			butAdmin.setBackgroundResource(R.drawable.but_red_bg);
			butOb.setVisibility(View.VISIBLE);
			tvWarning.setVisibility(View.VISIBLE);
		}else{
			//observer
			tvAuthor.setText(R.string.you_are_ob);
			butAdmin.setVisibility(View.GONE);
			butOb.setVisibility(View.VISIBLE);
			tvWarning.setVisibility(View.INVISIBLE);
		}
		
		if((mPower != null) && (mPower.power >= 0)){
			int bat_img = getBatteryImgRes(mPower.power);
			tvBattery.setText(""+mPower.power+"%");
			Drawable[] drawables = tvBattery.getCompoundDrawables();
			Rect rect = drawables[0].getBounds();
			Drawable newdraw = getResources().getDrawable(bat_img);
			newdraw.setBounds(rect);
			tvBattery.setCompoundDrawables(newdraw, null, null, null);
		}else{
			tvBattery.setText("?");
			Drawable[] drawables = tvBattery.getCompoundDrawables();
			Rect rect = drawables[0].getBounds();
			Drawable newdraw = getResources().getDrawable(R.drawable.bat_icon_unknown);
			newdraw.setBounds(rect);
			tvBattery.setCompoundDrawables(newdraw, null, null, null);
		}
		
		if(mSetData == null)
			return;
		
		if(mDev.admin != 2){
			if(!mSetData.active){
				tvWarning.setVisibility(View.VISIBLE);
				tvWarning.setText(R.string.dev_activated_warning);
				tvWarning.setBackgroundColor(0x80FF0000);
			}else{
				tvWarning.setVisibility(View.INVISIBLE);
			}
		}
		
		String phone = mSetData.mobile;
		if((phone == null) || phone.isEmpty()){
			phone = "";
		}
		tvPhone.setText(phone);
		updateFace();
	}
	
	private int getBatteryImgRes(int percent){
		if(percent < 10){
			return R.drawable.bat_icon_000;
		}else if(percent < 20){
			return R.drawable.bat_icon_010;
		}else if(percent < 30){
			return R.drawable.bat_icon_020;
		}else if(percent < 40){
			return R.drawable.bat_icon_030;
		}else if(percent < 50){
			return R.drawable.bat_icon_040;
		}else if(percent < 60){
			return R.drawable.bat_icon_050;
		}else if(percent < 70){
			return R.drawable.bat_icon_060;
		}else if(percent < 80){
			return R.drawable.bat_icon_070;
		}else if(percent < 90){
			return R.drawable.bat_icon_080;
		}else if(percent < 100){
			return R.drawable.bat_icon_090;
		}else{
			return R.drawable.bat_icon_100;
		}
	}
	
	private void updateFace(){
		String[] args = new String[1];
		args[0] = mDev.id;
		DEV_FACE face = (DEV_FACE) mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, args);
		if(face == null){
			vPhoto.setImageResource(R.drawable.default_photo);
			vPhoto.setBackgroundResource(R.drawable.photo_bg);
		}else if((face.bitmap != null) && !face.bitmap.isRecycled()){
			vPhoto.setImageBitmap(face.bitmap);
			vPhoto.setBackgroundColor(getResources().getColor(R.color.TRANSPARENT));
		}else{
			vPhoto.setImageResource(R.drawable.default_photo);
			vPhoto.setBackgroundResource(R.drawable.photo_bg);
		}
	}
	
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				String t = intent.getStringExtra("type");
				String tid = intent.getStringExtra("tid");
				if(t.equals(DataManager.F_DEVICEFACE) && tid.equals(mDev.id)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					if(code != 200){
						mApp.dismissWaiting();
						mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.dismissWaiting();
						mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
					}else{
						mApp.dismissWaiting();
						updateFace();
					}
				}else if(t.equals(DataManager.F_DEVICELIST) && tid.equals(mDev.id)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					String cmd = intent.getStringExtra("cmd");
					if(code != 200){
						mApp.dismissWaiting();
						mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.dismissWaiting();
						mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
					}else{
						mApp.dismissWaiting();
						if(cmd.equals("COMMIT_DEVICE_INTEREST_ABORT")){
							mApp.showAlertDialog(DeviceManagerActivity.this, getResources().getString(R.string.commit_ok), R.string.ok,
									new View.OnClickListener() {
										
										@Override
										public void onClick(View arg0) {
											Intent i = new Intent("COMMIT_DEVICE_INTEREST_ABORT");
											i.putExtra("tid", mDev.id);
											DeviceManagerActivity.this.setResult(RESULT_OK,i);
											finish();
										}
									});
						}else{
							if(cmd.equals("COMMIT_DEVICE_ADMIN_ABORT")){
								mApp.getDataManager().setUserData(DataManager.F_DEVICELIST, null);
								mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
							}
							updateData();
							updateView();
							mApp.showAlertDialog(DeviceManagerActivity.this, getResources().getString(R.string.commit_ok), R.string.ok, null);
						}
					}
				}
			}else if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);	
				if(t.equals(DataManager.F_DEVICELIST)){
					if(s){
						updateData();
						updateView();
					}
				}else if(t.equals(DataManager.F_DEVICE_SETTINGS)){
					String tid = intent.getStringExtra("tid");
					if(tid.equals(mDev.id)){
						if(refreshing != null){
							updateRefreshFlag(t);
							if(refreshing == null){
								mApp.dismissWaiting();
								updateData();
								updateView();
							}
						}else if(s){
							updateData();
							updateView();
						}
					}
				}else if(t.equals(DataManager.F_DEVICE_POWER)){
					String tids = intent.getStringExtra("tidarr");
					try {
						JSONArray tidarr = new JSONArray(tids);
						int len = tidarr.length();
						for(int i = 0; i < len; i++){
							String tid = tidarr.getString(i);
							if(tid.equals(mDev.id)){
								if(refreshing != null){
									updateRefreshFlag(t);
									if(refreshing == null){
										mApp.dismissWaiting();
										updateData();
										updateView();
									}
								}else if(s){
									updateData();
									updateView();
								}
								break;
							}
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else if(t.equals(DataManager.F_DEVICEFACE)){
					String tid = intent.getStringExtra("tid");
					if(tid.equals(mDev.id) && s){
						updateFace();
					}
				}
			}
		}
	};

	private void updateRefreshFlag(String clear){
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		case R.id.but_share:{
			String uri = HttpConf.getDeviceInterestUri(mDev.id, mDev.name);
			Intent i = new Intent(this,QRCodeActivity.class);
			i.putExtra("type", QRCodeActivity.TYPE_DEVICE);
			i.putExtra("uri", uri);
			i.putExtra("mid",-1);
			startActivity(i);
			finish();
		}break;
		case R.id.edit:{
			Intent i = new Intent(this,DeviceManagerEdit.class);
			i.putExtra("dev", mDev);
			startActivity(i);
		}break;
		
		case R.id.check_manufactrue:{
			Intent i = new Intent(this,DeviceDetailActivity.class);
			i.putExtra("dev", mDev);
			startActivity(i);
		}break;
		
		case R.id.photo:{
			mApp.showPickPhotoWin(this, new OnClickListener(){

				@Override
				public void onClick(View v) {
					if(v.getId() == R.id.pick_cam){
						String path = mApp.getUploadFacePreCropFileName();
						if(path == null)
							return;
						Uri imageUri = Uri.parse("file://" + path);
						Intent takephoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						takephoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						startActivityForResult(takephoto,RESULT_CODE_CAMERA);
					}else if(v.getId() == R.id.pick_album){
						String path = mApp.getUploadFaceFileName();
						if(path == null)
							return;
						Uri imageUri = Uri.parse("file://" + path);
						Intent cropAlbum = new Intent(Intent.ACTION_GET_CONTENT);
						cropAlbum.setType("image/*");
						cropAlbum.putExtra("crop", "true");
						cropAlbum.putExtra("aspectX", 1);
						cropAlbum.putExtra("aspectY", 1);
						cropAlbum.putExtra("outputX", 300);
						cropAlbum.putExtra("outputY", 300);
						cropAlbum.putExtra("scale", true);
						cropAlbum.putExtra("return-data", false);
						cropAlbum.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						cropAlbum.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
						startActivityForResult(cropAlbum,RESULT_CODE_ALBUM);
					}
				}
				
			});
		}break;
		
		case R.id.but_admin:{
			String name = mDev.name;
			if((name == null) || name.isEmpty()){
				name = getResources().getString(R.string.noName);
			}
			name = "\""+name+"\"";
			if(mDev.admin == 1){
				//abort admin
				mApp.showCustomizedDialog(this, getResources().getString(R.string.abandon_admin),
						getResources().getString(R.string.abandon_admin_confirmation, name),
						getResources().getString(R.string.Yes), getResources().getString(R.string.No),
						new View.OnClickListener(){

							@Override
							public void onClick(View v) {
								if(v.getId() == R.id.alert_but1){
									if(abortAdmin() == false){
										mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
									}else{
										mApp.showWaitting(DeviceManagerActivity.this, null);
									}
								}
							}
					
				});
			}else if(mDev.admin == 2){
				//apply
				mApp.showCustomizedDialog(this, getResources().getString(R.string.acquire_admin),
						getResources().getString(R.string.acquire_admin_confirmation,name),
						getResources().getString(R.string.conitnue), getResources().getString(R.string.back),
						new View.OnClickListener(){

							@Override
							public void onClick(View v) {
								if(v.getId() == R.id.alert_but1){
									if(applyAdmin() == false){
										mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
									}else{
										mApp.showWaitting(DeviceManagerActivity.this, null);
									}
								}
							}
					
				});
			}
		}break;
		
		case R.id.but_ob:{
			//abort interest
			String name = mDev.name;
			if((name == null) || name.isEmpty()){
				name = getResources().getString(R.string.noName);
			}
			name = "\""+name+"\"";
			mApp.showCustomizedDialog(this, getResources().getString(R.string.abandon_ob),
					getResources().getString(R.string.abandon_ob_confirmation,name),
					getResources().getString(R.string.Yes), getResources().getString(R.string.No),
					new View.OnClickListener(){

						@Override
						public void onClick(View v) {
							if(v.getId() == R.id.alert_but1){
								if(abortInterest() == false){
									mApp.showAlertDialog(DeviceManagerActivity.this, R.string.commit_err);
								}else{
									mApp.showWaitting(DeviceManagerActivity.this, null);
								}
							}
						}
				
			});
		}break;
		}
	}
	
	private boolean applyAdmin(){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "bindadmin");
			commit.put("tid", mDev.id);
			commit.put("devicename", mDev.name);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICELIST, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}
	
	private boolean abortInterest(){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "abortinterest");
			commit.put("tid", mDev.id);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICELIST, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}
	
	private boolean abortAdmin(){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "abortadmin");
			commit.put("tid", mDev.id);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICELIST, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}

	private int RESULT_CODE_ALBUM = 21;
	private int RESULT_CODE_CAMERA = 22;
	private int RESULT_CODE_CROP_CAMERA = 23;
	
	@Override
	public void onActivityResult(int requestCode, int result, Intent intent){
		if((RESULT_CODE_ALBUM == requestCode) || (RESULT_CODE_CROP_CAMERA == requestCode)){
			if(RESULT_OK == result){
				String path = mApp.getUploadFaceFileName();
				if(path == null)
					return;
				File f = new File(path);
				if(f.exists()){
					boolean ok = false;
					try {
						JSONObject d = new JSONObject();
					
						d.put("path", path);
						d.put("tid", mDev.id);
						ok = mApp.getDataManager().commitData(DataManager.F_DEVICEFACE, d);
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if(ok){
						mApp.showWaitting(this, null);
					}else{
						mApp.showAlertDialog(this, R.string.upPhoto_err);
					}
				}
			}
		}else if(RESULT_CODE_CAMERA == requestCode){
			if(RESULT_OK == result){
				String precrop = mApp.getUploadFacePreCropFileName();
				String path = mApp.getUploadFaceFileName();
				if((precrop == null) || (path == null))
					return;
				
				Uri preCropUri = Uri.parse("file://" + precrop);
				Uri imageUri = Uri.parse("file://" + path);
				Intent cropIntent = new Intent("com.android.camera.action.CROP");
				cropIntent.setDataAndType(preCropUri, "image/*");
				cropIntent.putExtra("crop", "true");//可裁剪
				cropIntent.putExtra("aspectX", 1);
				cropIntent.putExtra("aspectY", 1);
				cropIntent.putExtra("outputX", 300);
				cropIntent.putExtra("outputY", 300);
				cropIntent.putExtra("scale", true);
				cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				cropIntent.putExtra("return-data", false);//若为false则表示不返回数据
				cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
				//cropIntent.putExtra("noFaceDetection", true); 
				startActivityForResult(cropIntent, RESULT_CODE_CROP_CAMERA);
			}
		}
	}
}
